package com.shareyi.simpleserver.servlet;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.Map;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.ResourceNotFoundException;

import com.shareyi.simpleserver.core.HttpRequest;
import com.shareyi.simpleserver.core.HttpResponse;
import com.shareyi.simpleserver.core.SimpleHttpServer;

public class DefaultVelocityServlet extends SimpleServlet {
	//初始化并取得Velocity引擎
	private VelocityEngine ve;
	
	@Override
	public void init(Map<String, String> servletConfig) throws ServletException {
		ve=new VelocityEngine();
		ve.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH,SimpleHttpServer.getServerInstance().getBasePath());
		ve.setProperty(Velocity.INPUT_ENCODING,"utf-8");
		ve.setProperty(Velocity.OUTPUT_ENCODING,"utf-8");
		ve.init();
	}

	@Override
	public void service(HttpRequest httpRequest, HttpResponse response)
			throws ServletException, IOException {
			Map<String,Object> root=httpRequest.getAttributeMap();
			root.putAll(httpRequest.getParameterMap());
			
			VelocityContext context=new VelocityContext();
			context.put("request",httpRequest);
			context.put("reqScope",root);
			try
			{
			Template t= ve.getTemplate(httpRequest.getUrl());
			t.merge(context, response.getPrintWriter());
			}catch(ResourceNotFoundException ee)
			{
				response.setStatusCode(HttpURLConnection.HTTP_NOT_FOUND);
			}
	}

}
